import os
import datetime
import hashlib
import shutil

# 递归获取指定目录下的所有文件
def getFileName(directory):
    file_list = []
    for dir_name, sub_dir_list, file_name_list in os.walk(directory):
        if len(file_name_list) > 0:
            for f_name in file_name_list:
                full_file_name = dir_name + "\\" + f_name
                file_list.append(full_file_name)
    return file_list

# 文件批量重命名  3.txt  3_YYYY_MM_DD.txt
def fileRename():
    time = datetime.datetime.now().strftime("_%Y_%m_%d")
    files = getFileName(r"D:\pythonLearn\文件操作\北京")
    for f_name in files:
        name = f_name.split(".")[0]
        suffix = f_name.split(".")[1]
        new_file_name = name + time + "." + suffix
        os.rename(f_name, new_file_name)

# 文件MD5校验  md5sum 文件名称
def fileMD5(file):
    md5 = hashlib.md5()
    with open(file, mode="rb") as fobj:
        for line in fobj:
            md5.update(line)
    return md5.hexdigest()

# 文件差异检测
def fileDiff():
    bj_file_list = getFileName(r"D:\pythonLearn\文件操作\北京")
    for src_file in bj_file_list:
        dest_file = src_file.replace("北京", "上海")
        if not os.path.exists(dest_file):
            print("文件【%s】丢失!!!" % src_file)
            shutil.copy(src_file, dest_file)
        else:
            src_file_md5 = fileMD5(src_file)
            dst_file_md5 = fileMD5(dest_file)
            if dst_file_md5 != src_file_md5:
                print("文件【%s】数据不完整!!!!" % src_file)
                shutil.copy(src_file, dest_file)


if __name__ == '__main__':
    fileDiff()